<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\service\TenIM;
use think\Db;
/**
 * 写手商品
 *
 * @icon fa fa-circle-o
 */
class Writergoodssh extends Backend
{

    /**
     * Writergoods模型对象
     * @var \app\admin\model\Writergoods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Writergoods;
         
        $this->view->assign("statusList", ["审核中","正常","下架"]);

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
     public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
             ->alias("m") 
            ->where($where)
            ->field("m.*,mb.dream_id,mb.username,m.status as 'm.status'")
            ->join("membe mb","mb.membe_id=m.uid","left")
            ->where("zz_status",2)
            ->where("m.title is not null")
            // ->where("m.status",'>',0)
            ->order("up_time desc")
            ->paginate($limit)->each(function ($data){
                $data["refuse_msg"] = empty($data["refuse_msg"])?"-":$data["refuse_msg"];
                //  $data["dream_id"] = db("membe")->where("membe_id",$data["uid"])->value("dream_id");
                 return $data;
            });
            
            
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    
    
       
    public function edit($ids = null)
    {
                
                        
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        
               
                        
                        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            
    
            
            if($params["status"] ==0){
                $this->error("暂不支持修改");
            }
            
        
        
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            
            //订单状态更改？
         $uid = $row["uid"];
         $openid = db("membe")->where("membe_id",$row["uid"])->value("openid");

         if($params['status'] == 1){
            $params["is_w"] = 0;
            $msg = '写手认证审核通过！';
            $title = "写手认证审核通过";
            // // 保存写手标签
            // $tags = [];
            // $zids = [];
            // $zsidsss = [];
           
              if(!empty($openid)){
                    $this->wx_msg($openid,$title,"请尽快完善相关约稿设置");
                }
                //同时 推送1条消息

         
            
                    
                    $new_arr_json = [];
                    $new_arr_json["type"] = 15;
                    $new_arr_json["aid"] = $row['id'];
                    $new_arr_json["uid"] =  $row["uid"];
                    // $new_arr_json["username"] = $user['username'];
                    $new_arr_json["title"] = '您的橱窗申请已通过';//urldecode($info['title']);
                    $new_arr_json["left_1"] = "通知时间：";
                    $new_arr_json["left_1_val"] = date("Y-m-d H:i:s");
                    
                    $new_arr_json["left_2"] = "通过编号：";
                    $new_arr_json["left_2_val"] = time();
                    
                 
                    (new TenIM)->sendSystemMsg($uid,'type'.json_encode($new_arr_json));
                     
             
             
        }else if($params['status'] == 2){
            $params["is_w"] = 1;
             $msg = $params['refuse_msg'];
             $title = "写手认证审核失败";
           
             if(!empty($openid)){
                  $data = $this->wx_msg($openid,$title,$msg);
              }
              
          
                            $params["is_w"] = 1;
                            $new_arr_json = [];
                            $new_arr_json["type"] = 888;
                            $new_arr_json["aid"] = $row['id'];
                            $new_arr_json["uid"] =  $row["uid"];
                            // $new_arr_json["username"] = $user['username'];
                            $new_arr_json["title"] = '您的账号涉嫌违规';//urldecode($info['title']);
                            $new_arr_json["left_1"] = "处理方式：";
                            $new_arr_json["left_1_val"] = "下架";
                            
                            $new_arr_json["left_2"] = "处理时间：";
                            $new_arr_json["left_2_val"] = date("Y年m月d日");
                            
                            $new_arr_json["left_3"] = "违规原因：";
                            $new_arr_json["left_3_val"] = urldecode($params["refuse_msg"]);
                            
                            $new_arr_json["left_4"] = "温馨提示：";
                            $new_arr_json["left_4_val"] = $params["tips"];
                            $new_arr_json["path"] = "/pages/user/release";
                            (new TenIM)->sendUserMsg($row["uid"],"sysmsg",'type'.json_encode($new_arr_json));
                             
                            db("weigui")->insert(["title"=>urldecode($params["refuse_msg"]),"uid"=>$new_arr_json["uid"],"content"=>json_encode($new_arr_json)]);
                            
             
                      
                         
               
                //  if(time()>1730217600){
                //     $new_arr_json = [];
                //     $new_arr_json["type"] = 8;
                //     $new_arr_json["aid"] = $row["uid"];
                //     // $new_arr_json["username"] = $user['username'];
                //     $new_arr_json["title"] = '写手认证审核失败';//urldecode($info['title']);
                //     $new_arr_json["left_1"] = "通知时间";
                //     $new_arr_json["left_1_val"] = date("Y-m-d H:i:s");
                    
                //     $new_arr_json["left_2"] = "失败原因";
                //     $new_arr_json["left_2_val"] = $data['refuse_msg'];
                //     (new TenIM)->sendSystemMsg($row['uid'],'type'.json_encode($new_arr_json));
                     
                // }else{
                //      (new TenIM)->sendSystemMsg($row['uid'],$title,$msg);
                // }
                     
            //  db("membe")->where('membe_id',$row['uid'])->update(['is_writer'=>0,'update_time'=>time()]);
        }
            
        $params["sh_time"] = date("Y-m-d H:i:s");
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
     //訂閲消息消息推送
     public function wx_msg($openid,$title,$desc){ 
         
            $templateId = 'rw8um2woPZuyWmlZFrRYLslXmrIHd1MmcUTry7Ci3Yw';
            $data = array(
                'thing1' => array('value' => $title),
                'time3' => array('value' => date('Y-m-d H:i:s', time())),
                'thing4' => array('value' => mb_substr($desc,0,15)),
            );
            $send = array(
                "touser" => $openid,
                "page"=>"pages/index/index",
                "template_id" => $templateId,
                "data" => $data,
            );
         
            $access_token = getaccess_tonken();

            $data = urldecode(json_encode($send));
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
            // $ret = Http::post($url, );
            $admin = curl_get($url,$type = 'json',$data);
            return $admin;
     }
     
      public function err_z_auth($openid,$title,$data){ 
            $templateId = 'PzrRvEAGLoXhy7DzBPE9spkaKPfGq_8k9uVQo2wBukU';
            $data = array(
                'thing1' => array('value' =>$title),
                'thing2' => array('value' =>mb_strlen($data)>14?mb_substr($data,0,12)."***":$data),
                'time3' => array('value' =>date("Y-m-d H:i")),
            );
      
            return $this->gz_type($openid,$templateId,$data);
     }
     
     public function gz_type($openid,$templateId,$data){
         /*
         "miniprogram":{
             "appid":"xiaochengxuappid12345",
             "pagepath":"index?foo=bar"
           },
         **/
            $send = array(
                "touser" => $openid,
                "template_id" => $templateId,
                "data" => $data,
                "miniprogram"=>[
                    "appid"=>"wxa2a0734b14927ebf",
                    "pagepath"=>"pages/index/index",
                ]
                
            );
            
       
            $access_token = getaccess_tonken();
            $data = urldecode(json_encode($send));
            $url= "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
            $admin = curl_get($url,$type = 'json',$data);
            return $admin;
     }

}
